import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'

import { getTimeStamp } from '@/utils/auth'

import router from '@/router'

// import store from '@/store'

// 设置token过期判定时间
const timeOut = 3600

// 判断token是否过期的函数
function isTokenOut() {
  const now = Date.now()
  const before = getTimeStamp()
  console.log('判断token')
  console.log(before)

  return (now - before) / 1000 > timeOut
}

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000

})

// 请求拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['Authorization'] = `Bearer ${store.getters.token}`

    // 判断token是否过期
    if (isTokenOut()) {
      store.dispatch('user/loginOut')
      router.push('/login')
      return Promise.reject(new Error('token超时了'))
    }
  }

  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(response => {
  // 结构返回数据，看返回数据是否正常
  const { success, message, data } = response.data

  if (success) {
    console.log(data)
    return data
  } else {
    Message.error(message)

    return Promise.reject(new Error(message))
  }
}, error => {
  Message.error(error.message)
  return Promise.reject(new Error(error))
})

export default service
